package httpsign

import (
	"context"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// Handler http签名中间件，用于验证http请求的签名
func Handler(opts ...Option) middleware.Middleware {
	o := &options{
		signMatch: MatchSignFuncMap{}, //签名匹配函数
	}

	for _, opt := range opts {
		opt(o)
	}

	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			if len(o.signMatch) == 0 {
				return handler(ctx, req)
			}
			if tr, ok := transport.FromServerContext(ctx); ok {
				fn, ok := o.signMatch[tr.Operation()]
				if !ok {
					return handler(ctx, req)
				}
				ht, ok := http.RequestFromServerContext(ctx)
				if err := fn(ctx, ht); err != nil {
					return nil, err
				}
			}
			return handler(ctx, req)
		}
	}
}
